import { ErrorPayload, isErrorPayload, isSendToPayload, isSendToRoomPayload, Message, MessageType, RequestPayload, ResponsePayload, SendToPayload, SendToRoomPayload } from "@core/types";

export function toMessage(from: string, data: any, request: RequestPayload) {
    if (data instanceof Error) {
        return toError(from, data, request);
    }
    if (isErrorPayload(data)) {
        return {
            type: MessageType.ERROR,
            payload: data
        } as Message<ErrorPayload>
    }
    else if (isSendToPayload(data)) {
        return {
            type: MessageType.SENDTO,
            payload: data
        } as Message<SendToPayload>
    }
    else if (isSendToRoomPayload(data)) {
        return {
            type: MessageType.SENDTOROOM,
            payload: data
        } as Message<SendToRoomPayload>
    } else {
        return toReponse(from, data, {}, request)
    }
}

export function toError(from: string, e: Error, request: RequestPayload): Message<ErrorPayload> {
    return {
        type: MessageType.ERROR,
        payload: {
            appid: request.appid,
            reqid: request.reqid,
            message: e.message,
            stack: e.stack || "",
            from: from,
            data: Buffer.from(JSON.stringify({}))
        }
    }
}

export function toReponse(from: string, data: any, headers: any, request: RequestPayload): Message<ResponsePayload> {
    return {
        type: MessageType.RESPONSE,
        payload: {
            appid: request.appid,
            reqid: request.reqid,
            data: Buffer.from(JSON.stringify(data)),
            headers: Buffer.from(JSON.stringify(headers)),
            from: from
        }
    }
}


export function toSendTo(payload: SendToPayload): Message<SendToPayload> {
    return {
        type: MessageType.SENDTO,
        payload: payload
    }
}

export function toSendToRoom(payload: SendToRoomPayload): Message<SendToRoomPayload> {
    return {
        type: MessageType.SENDTOROOM,
        payload: payload
    }
}